package com.example.demo.interceptor;

import com.example.demo.annotation.Unauth;
import com.example.demo.common.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {

	List<String> allowUri = new ArrayList<String>();// 不需要拦截的请求

	private static final String WEB_URL = "https://www.panguyr.com";
	// 日志
	protected static Logger log = LogManager.getLogger(LoginInterceptor.class);
	private static final ThreadLocal<StopWatch> stopWatchLocal = new NamedThreadLocal<StopWatch>(
			"ThreadLocal StopWatch");

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3) {
		String uri = request.getRequestURI();
		try {
			if (uri.indexOf("admin/public/api") == -1
					&& uri.indexOf("admin/sales/receiveBankCardNotify") == -1
					&& uri.indexOf("admin/sales/receivePayNotify") == -1) {
				HttpSession session = request.getSession();
				if (session != null) {
					Object sessionObj = request.getSession().getAttribute(
							Constant.AUTH_USER);
					if (sessionObj != null) {
						StopWatch stopWatch = stopWatchLocal.get();
						if (stopWatch != null) {
							stopWatch.stop();
							String currentPath = request.getRequestURI();
							String queryString = request.getQueryString();
							queryString = queryString == null ? "" : "?"
									+ queryString;
							log.info("access url path:" + currentPath
									+ queryString + " |time:"
									+ stopWatch.getTotalTimeMillis() + "ms");
							stopWatchLocal.set(null);
						}
					}
				}
			}
		} catch (Exception e) {

		}

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView modelAndView) {
		String uri = request.getRequestURI();
		try {
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase(
							"XMLHttpRequest")) { // 如果是ajax请求响应头会有x-requested-with
				if (modelAndView != null) {
					PrintWriter out = response.getWriter();
					out.print("asdfdsa");
					out.flush();
					out.close();
				} else {
					Object sessionObj = request.getSession().getAttribute(
							"authuser");
					if (sessionObj == null) {
						if (isProductEnvironment()) {
							response.sendRedirect(WEB_URL
									+ "/admin/hello.html");
						} else {
							response.sendRedirect("/admin/hello.html");
						}
					}
				}
			}
		} catch (Exception e) {

		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) {
		String uri = request.getRequestURI();
		try {
			if ("/".equals(uri)) {
				if (isProductEnvironment()) {
					response.sendRedirect(WEB_URL + "/admin/hello.html");
				} else {
					response.sendRedirect("/admin/hello.html");
				}
				return false;
			}
			boolean intercept = true;
			for (String url : allowUri) {
				if (uri.indexOf(url) != -1) {
					intercept = false;
					break;
				}
			}

			if (intercept) {
				Object sessionObj = request.getSession().getAttribute(
						Constant.AUTH_USER);
				if (sessionObj != null) {
					StopWatch stopWatch = new StopWatch(handler.toString());
					stopWatchLocal.set(stopWatch);
					stopWatch.start(handler.toString());
					log.info("stopWatch  start.......");
					return true;
				} else {
					if (isProductEnvironment()) {
						response.sendRedirect(WEB_URL
								+ "/admin/hello.html");
					} else {
						response.sendRedirect("/admin/hello.html");
					}

					return false;
				}
			}
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public List<String> getAllowUri() {
		return allowUri;
	}

	public void setAllowUri(List<String> allowUri) {
		this.allowUri = allowUri;
	}

	protected boolean isProductEnvironment() {
		String ENV_TYPE = "T";
		if (!StringUtils.isEmpty(ENV_TYPE) && (!"P".equals(ENV_TYPE))) {
			// 非生产环境
			return false;
		} else {
			// 生产环境
			return true;
		}
	}

}